//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client;

import java.util.List;

import tv.dyndns.kishibe.client.packet.PacketRoomKey;
import tv.dyndns.kishibe.client.packet.PacketServerStatus;
import tv.dyndns.kishibe.client.ui.WidgetMultiItemSelector;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PanelLobby extends VerticalPanel implements ClickHandler {
	private final SceneLobby scene;
	private Grid gridStatus;
	private Grid gridRecord;
	private final HorizontalPanel infoPanel = new HorizontalPanel();
	private final VerticalPanel playerHistoryPanel = new VerticalPanel();
	private final TextBox textBoxPlayerName = new TextBox();
	private final ListBox listBoxLevelName = new ListBox();
	private final ListBox listBoxLevelNumber = new ListBox();
	private final ListBox listBoxPrefecture = new ListBox();
	private final WidgetMultiItemSelector multiItemSelectorGenre = new WidgetMultiItemSelector("ジャンル", Constant.NAMES_OF_GENRE, 3);
	private final WidgetMultiItemSelector multiItemSelectorType = new WidgetMultiItemSelector("出題形式", Constant.NAMES_OF_TYPE_WITH_RANDOM_FLAG, 5);
	private final TextBox textBoxGreeting = new TextBox();
	private final ListBox listBoxDifficultSelect = new ListBox();
	private final CheckBox checkBoxNewProblem = new CheckBox("新問を出題する");
	private final Button buttonGameVsCom = new Button("COM対戦", this);
	private final Button buttonGameAllClass = new Button("全体対戦", this);
	private final Button buttonGameEvent = new Button("イベント対戦", this);
	private final TextBox textBoxEventName = new TextBox();
	private final Button buttonShowEventRooms = new Button("参照", this);
	private final CheckBox checkBoxPublicEvent = new CheckBox("イベント戦を全体から参照できるようにする");
	private final HorizontalPanel panelThemeMode = new HorizontalPanel();
	private final ListBox listBoxTheme = new ListBox();
	private final Button buttonGameTheme = new Button("テーマモード", this);
	private static final String LEVEL_NAME[] = { "修練", "見習", "初級", "中級", "上級", "魔導", "大魔導", "賢者", "大賢者", "青銅", "白銀", "黄金", "白金", "金剛", "天青", "紅玉", "翡翠", "黄玉", "紫宝" };
	private static final String LEVEL_NAME_GOD = "かみ";
	private static final String LEVEL_NAME_EMPEROR = "エンペラー";
	private static final String LEVEL_NAME_KING = "キング";

	private void setEnabled(boolean enabled) {
		buttonGameVsCom.setEnabled(enabled);
		buttonGameAllClass.setEnabled(enabled);
		buttonGameEvent.setEnabled(enabled);
		textBoxPlayerName.setEnabled(enabled);
		listBoxLevelName.setEnabled(enabled);
		listBoxLevelNumber.setEnabled(enabled);
		listBoxPrefecture.setEnabled(enabled);
		multiItemSelectorGenre.setEnabled(enabled);
		multiItemSelectorType.setEnabled(enabled);
		textBoxGreeting.setEnabled(enabled);
		listBoxDifficultSelect.setEnabled(enabled);
		textBoxEventName.setEnabled(enabled);
		listBoxTheme.setEnabled(enabled);
		buttonGameTheme.setEnabled(enabled);
		checkBoxNewProblem.setEnabled(enabled);
	}

	private boolean checkContents() {
		if (textBoxPlayerName.getText().trim().length() == 0) {
			return false;
		}

		if (textBoxGreeting.getText().trim().length() == 0) {
			return false;
		}

		if (getGenre() == 0) {
			return false;
		}

		if (getType() == 0) {
			return false;
		}

		return true;
	}

	public PanelLobby getInstance() {
		return this;
	}

	public PanelLobby(SceneLobby sceneRegistration) {

		if (Constant.FIXED_CLASS_LEVEL >= 0) {
			UserData.getInstance().setClassLevel(Constant.FIXED_CLASS_LEVEL);
		}

		this.scene = sceneRegistration;

		setWidth("800px");
		setVerticalAlignment(ALIGN_MIDDLE);
		setHorizontalAlignment(ALIGN_CENTER);

		final HTML html = new HTML("クイズマジックアカデミーシミュレーションゲーム QMAClone by nodchip(ノドチップ)<br/>バグ報告・要望は<a href='http://kishibe.dyndns.tv/qmaclone/wiki/wiki.cgi'>こちら</a>にお願いいたします。");

		final UserData record = UserData.getInstance();

		// 説明文
		add(html);

		final HTML htmlGoogle = new HTML("<!-- Search Google --><center><form method='get' action='http://www.google.co.jp/custom' target='google_window'><table bgcolor='#ffffff'><tr><td nowrap='nowrap' valign='top' align='left' height='32'><a href='http://www.google.com/'><img src='http://www.google.com/logos/Logo_25wht.gif' border='0' alt='Google' align='middle'></img></a><label for='sbi' style='display: none'>検索用語を入力</label><input type='text' name='q' size='31' maxlength='255' value='' id='sbi'></input><label for='sbb' style='display: none'>検索フォームを送信</label><input type='submit' name='sa' value='検索' id='sbb'></input><input type='hidden' name='client' value='pub-2044095449285503'></input><input type='hidden' name='forid' value='1'></input><input type='hidden' name='channel' value='8108143125'></input><input type='hidden' name='ie' value='UTF-8'></input><input type='hidden' name='oe' value='UTF-8'></input><input type='hidden' name='cof' value='GALT:#008000;GL:1;DIV:#336699;VLC:663399;AH:center;BGC:FFFFFF;LBGC:336699;ALC:0000FF;LC:0000FF;T:000000;GFNT:0000FF;GIMP:0000FF;LH:30;LW:331;L:http://kishibe.dyndns.tv/qmaclone/logo.png;S:http://kishibe.dyndns.tv/qmaclone/;FORID:1'></input><input type='hidden' name='hl' value='ja'></input></td></tr></table></form></center><!-- Search Google -->");
		add(htmlGoogle);

		// 情報
		final HTML htmlInfo = new HTML("お知らせ<br/>テーマモードの編集は申請式となりました。プレイ回数100回以上の方は設定画面から申請できます。");
		add(htmlInfo);

		// クラス表示
		final HorizontalPanel panelClass = new HorizontalPanel();
		panelClass.setVerticalAlignment(ALIGN_MIDDLE);

		final Label labelClass = new Label("階級(自己申告)");
		panelClass.add(labelClass);

		// 階級の数字
		listBoxLevelNumber.setTitle("名前欄に表示する階級を設定します。階級は表示のみでゲーム内容には一切関係しません。");
		listBoxLevelNumber.setWidth("60px");
		for (int i = 1; i <= 10; ++i) {
			listBoxLevelNumber.addItem("" + i);
		}
		panelClass.add(listBoxLevelName);

		int levelNumber = record.getLevelNumber();
		if (levelNumber == Integer.MAX_VALUE) {
			levelNumber = 0;
		}
		listBoxLevelNumber.setSelectedIndex(levelNumber);

		// 階級名
		listBoxLevelName.setTitle("名前欄に表示する階級を設定します。階級は表示のみでゲーム内容には一切関係しません。");
		listBoxLevelName.setWidth("100px");
		for (String levelName : LEVEL_NAME) {
			listBoxLevelName.addItem(levelName);
		}
		panelClass.add(listBoxLevelNumber);

		if (record.getRating() >= Constant.RATING_THRESHOLD_GOD) {
			listBoxLevelName.addItem(LEVEL_NAME_GOD);
		} else if (record.getRating() >= Constant.RATING_THRESHOLD_EMPEROR) {
			listBoxLevelName.addItem(LEVEL_NAME_EMPEROR);
		} else if (record.getRating() >= Constant.RATING_THRESHOLD_KING) {
			listBoxLevelName.addItem(LEVEL_NAME_KING);
		}

		int levelName = record.getLevelName();
		if (levelName == Integer.MAX_VALUE) {
			levelName = 0;
		}
		listBoxLevelName.setSelectedIndex(Math.min(levelName, listBoxLevelName.getItemCount() - 1));

		add(panelClass);

		// 地域
		{
			for (int i = 0; i < Constant.PREFECTURE_NAMES.length; ++i) {
				listBoxPrefecture.addItem(Constant.PREFECTURE_NAMES[i]);
			}

			final HorizontalPanel panel = new HorizontalPanel();
			panel.add(new Label("地域"));
			panel.add(listBoxPrefecture);

			final int prefecture = record.getPrefecture();
			listBoxPrefecture.setSelectedIndex(prefecture);
			listBoxPrefecture.setWidth("100px");
			add(panel);
		}

		// プレイヤー名入力
		final HorizontalPanel panelName = new HorizontalPanel();
		panelName.setVerticalAlignment(ALIGN_MIDDLE);

		final Label labelName = new Label("プレイヤー名");
		panelName.add(labelName);

		textBoxPlayerName.setTitle("ゲーム中に表示されるプレイヤー名を入力してください。全角半角問わず最大6文字までです。");
		textBoxPlayerName.setWidth("150px");
		textBoxPlayerName.setMaxLength(6);
		textBoxPlayerName.setText(record.getPlayerName());
		panelName.add(textBoxPlayerName);

		add(panelName);

		// ジャンル選択
		add(multiItemSelectorGenre);
		multiItemSelectorGenre.set(UserData.getInstance().getGenre());

		// ジャンル初期選択
		add(multiItemSelectorType);
		multiItemSelectorType.set(UserData.getInstance().getType());

		// 挨拶
		final HorizontalPanel panelGreeting = new HorizontalPanel();
		panelGreeting.setVerticalAlignment(ALIGN_MIDDLE);

		final Label labelGreeting = new Label("対戦前の挨拶");
		panelGreeting.add(labelGreeting);

		textBoxGreeting.setTitle("対戦前に表示されるあいさつ文を入力してください。全角半角を問わず10文字までです。");
		textBoxGreeting.setWidth("200px");
		textBoxGreeting.setMaxLength(10);
		textBoxGreeting.setText(record.getGreeting());
		if (textBoxGreeting.getText() == "") {
			textBoxGreeting.setText("よろしく～！");
		}
		panelGreeting.add(textBoxGreeting);

		add(panelGreeting);

		// 難問の出題
		{
			final HorizontalPanel panel = new HorizontalPanel();
			panel.setVerticalAlignment(ALIGN_MIDDLE);
			panel.add(new Label("出題問題の難易度"));
			listBoxDifficultSelect.addItem("全難易度から出題する", "" + Constant.DIFFICULT_SELECT_NORMAL);
			listBoxDifficultSelect.addItem("難問を出題する", "" + Constant.DIFFICULT_SELECT_DIFFICULT);
			listBoxDifficultSelect.addItem("やや難問を出題する", "" + Constant.DIFFICULT_SELECT_LITTLE_DIFFICULT);
			listBoxDifficultSelect.addItem("やや易問を出題する", "" + Constant.DIFFICULT_SELECT_LITTLE_EASY);
			listBoxDifficultSelect.addItem("易問を出題する", "" + Constant.DIFFICULT_SELECT_EASY);

			final int difficultSelect = UserData.getInstance().getDifficultSelect();
			for (int i = 0; i < listBoxDifficultSelect.getItemCount(); ++i) {
				if (listBoxDifficultSelect.getValue(i).equals("" + difficultSelect)) {
					listBoxDifficultSelect.setSelectedIndex(i);
					break;
				}
			}

			panel.add(listBoxDifficultSelect);
			add(panel);
		}

		// 新問の出題
		{
			add(checkBoxNewProblem);
			checkBoxNewProblem.setValue(UserData.getInstance().getNewProblem());
		}

		// 各種ボタン配置
		{
			final HorizontalPanel panelButton = new HorizontalPanel();

			buttonGameVsCom.setTitle("COMと対戦する一人用モードです。問題とCOMの難易度は階級により変化します。");
			buttonGameAllClass.setTitle("他の参加者全員と対戦します。問題は全問題から出題されます。");

			panelButton.add(buttonGameVsCom);
			panelButton.add(buttonGameAllClass);
			add(panelButton);
		}

		// イベント名
		{
			buttonGameEvent.setTitle("ゲームを開始します。同じイベント名を指定した人とマッチングします。問題は全問題から出題されます。");
			textBoxEventName.setMaxLength(16);
			textBoxEventName.setTitle("イベント対戦で使用するイベント名を入力して下さい。");

			final HorizontalPanel panel = new HorizontalPanel();
			panel.setVerticalAlignment(ALIGN_MIDDLE);
			panel.add(buttonGameEvent);
			panel.add(new Label("イベント名"));
			panel.add(textBoxEventName);
			panel.add(buttonShowEventRooms);
			add(panel);

			checkBoxPublicEvent.setValue(UserData.getInstance().getPublicEvent());
			add(checkBoxPublicEvent);
		}

		{
			add(panelThemeMode);
			Service.Util.getInstance().getThemeModeThemes(callbackGetThemeModeThemes);
		}

		// サーバー状態
		gridStatus = new Grid(1, 1);
		gridStatus.setText(0, 0, "サーバーの状態を取得中です");

		setPlayerRecord();

		// 情報パネル
		infoPanel.add(gridStatus);
		infoPanel.add(gridRecord);
		infoPanel.add(playerHistoryPanel);
		add(infoPanel);
	}

	private final AsyncCallback<String[]> callbackGetThemeModeThemes = new AsyncCallback<String[]>() {
		public void onSuccess(String[] result) {
			panelThemeMode.add(buttonGameTheme);
			panelThemeMode.add(listBoxTheme);

			for (String theme : result) {
				listBoxTheme.addItem(theme);
			}
		}

		public void onFailure(Throwable caught) {
			caught.printStackTrace();
		}
	};

	public void setServerStatus(PacketServerStatus serverStatus) {
		final String[][] texts = { { "のべｾｯｼｮﾝ数", serverStatus.numberOfAllSessions + "ｾｯｼｮﾝ" }, { "稼動中ｾｯｼｮﾝ数", serverStatus.numberOfCurrentSessions + "ｾｯｼｮﾝ" }, { "のべﾌﾟﾚｲﾔｰ人数", serverStatus.numberOfAllPlayers + "人" }, { "プレイ中人数", serverStatus.numberOfCurrentPlayers + "人" }, { "ﾛｸﾞｲﾝﾕｰｻﾞｰ数", serverStatus.numberOfLoginUsers + "人" }, { "ﾄｯﾌﾟﾍﾟｰｼﾞｶｳﾝﾄ", serverStatus.topPageCounter + "" }, { "総問題数", serverStatus.numberOfProblems + "問" }, { "ｱｸﾃｨﾌﾞﾕｰｻﾞｰ数", serverStatus.numberOfActiveUsers + "" }, { "全体対戦待機中", serverStatus.numberOfPlayersInWhole + "" } };
		final int length = texts.length;
		gridStatus.addStyleName("gridFrame");
		gridStatus.addStyleName("gridFontNormal");
		gridStatus.resize(length, 2);
		for (int row = 0; row < length; ++row) {
			gridStatus.setText(row, 0, texts[row][0]);
			gridStatus.setText(row, 1, texts[row][1]);
		}
		// setCellWidth(gridStatus, "800px");
		// setCellHorizontalAlignment(gridStatus, ALIGN_CENTER);

		UserData.getInstance().setUserCode(serverStatus.userCode);

		SharedData.getInstance().setServerIgnoreUserCodes(serverStatus.serverIgnoreUserCodes);
	}

	public void setPlayerRecord() {
		final UserData record = UserData.getInstance();

		int playCount = record.getPlayCount();
		int highScore = record.getHighScore();
		int averageScore = record.getAverageScore();
		int victoryCount = record.getRating();
		final double averageRank = record.getAverageRank();
		final int classLevel = record.getClassLevel();
		int classNameIndex = classLevel / Constant.STEP_PER_CLASS_LEVEL;
		if (classNameIndex >= Constant.MAX_CLASS_LEVEL) {
			classNameIndex = Constant.MAX_CLASS_LEVEL;
		}

		if (record.getPlayCount() == Integer.MAX_VALUE) {
			record.setPlayCount(0);
			record.setHighScore(0);
			record.setAverageScore(0);
			record.setRating(0);

			playCount = 0;
			highScore = 0;
			averageScore = 0;
			victoryCount = 0;
		}

		String averageRankString;
		if (averageRank > 0.9) {
			averageRankString = "" + averageRank;
			if (averageRankString.length() > 4) {
				averageRankString = averageRankString.substring(0, 4);
			}
		} else {
			averageRankString = "未プレイ";
		}

		gridRecord = new Grid(7, 2);
		gridRecord.addStyleName("gridFrame");
		gridRecord.addStyleName("gridFontNormal");
		gridRecord.setText(0, 0, "ﾌﾟﾚｲ回数");
		gridRecord.setText(1, 0, "ﾊｲｽｺｱ");
		gridRecord.setText(2, 0, "平均ｽｺｱ");
		gridRecord.setText(3, 0, "ﾚｰﾃｨﾝｸﾞ");
		gridRecord.setText(4, 0, "平均順位");
		gridRecord.setText(5, 0, "クラス");
		gridRecord.setText(6, 0, "ﾕｰｻﾞｰｺｰﾄﾞ");
		gridRecord.setText(0, 1, "" + playCount);
		gridRecord.setText(1, 1, "" + highScore);
		gridRecord.setText(2, 1, "" + averageScore);
		gridRecord.setText(3, 1, "" + victoryCount);
		gridRecord.setText(4, 1, averageRankString);
		gridRecord.setText(5, 1, "(" + classLevel + ")" + Constant.getClassName(classNameIndex) + "組");

		// ここだけ突貫工事
		gridRecord.setWidget(6, 1, new Button("表示", clickHandlerUserCode));
	}

	private final ClickHandler clickHandlerUserCode = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			gridRecord.setText(6, 1, "" + UserData.getInstance().getUserCode());
		}
	};

	public void setLastestPlayers(String name[]) {
		playerHistoryPanel.clear();
		playerHistoryPanel.add(new Label("↓プレイヤー履歴↓"));

		for (int i = 0; i < name.length; ++i) {
			playerHistoryPanel.add(new Label(name[i]));
		}
	}

	public String getPlayerName() {
		String tempName = textBoxPlayerName.getText();

		if (tempName.length() > 6) {
			tempName = tempName.substring(0, 6);
		}
		final int selectedIndex = listBoxLevelName.getSelectedIndex();
		final String levelName = listBoxLevelName.getItemText(selectedIndex);
		final String levelNumber = listBoxLevelNumber.getItemText(listBoxLevelNumber.getSelectedIndex());

		final String title;
		if (selectedIndex >= LEVEL_NAME.length) {
			title = levelName;
		} else {
			title = levelName + levelNumber;
		}

		final int prefecture = listBoxPrefecture.getSelectedIndex();
		final int rating = UserData.getInstance().getRating();

		return title + " " + tempName + Constant.DELEMITER_PLAYER_NAME + Constant.PREFECTURE_NAMES[prefecture] + " " + rating;
	}

	public int getGenre() {
		return multiItemSelectorGenre.get();
	}

	public void setGenre(int genre) {
		multiItemSelectorGenre.set(genre);
	}

	public int getType() {
		return multiItemSelectorType.get();
	}

	public void setType(int type) {
		multiItemSelectorType.set(type);
	}

	public boolean getMultiGenre() {
		return multiItemSelectorGenre.isMultiSelect();
	}

	public boolean getMultiType() {
		return multiItemSelectorType.isMultiSelect();
	}

	public String getGreeting() {
		return textBoxGreeting.getText();
	}

	public String getEventName() {
		return textBoxEventName.getText();
	}

	public void setEventName(String eventName) {
		textBoxEventName.setText(eventName);
	}

	public boolean getPublicEvent() {
		return checkBoxPublicEvent.getValue();
	}

	public void setPublicEvent(boolean publicEvent) {
		checkBoxPublicEvent.setValue(publicEvent);
	}

	public int getDifficultSelect() {
		final int selectedIndex = listBoxDifficultSelect.getSelectedIndex();
		final String selectedItem = listBoxDifficultSelect.getValue(selectedIndex);
		return Integer.parseInt(selectedItem);
	}

	public boolean getNewProblem() {
		return checkBoxNewProblem.getValue();
	}

	public void setNewProblem(boolean newProblem) {
		checkBoxNewProblem.setValue(newProblem);
	}

	public String getThemeModeTheme() {
		return listBoxTheme.getItemText(listBoxTheme.getSelectedIndex());
	}

	private void showEventRooms() {
		Service.Util.getInstance().getEventRooms(callbackGetEventRooms);
	}

	private final AsyncCallback<List<PacketRoomKey>> callbackGetEventRooms = new AsyncCallback<List<PacketRoomKey>>() {
		public void onSuccess(List<PacketRoomKey> result) {
			showEventRooms(result);
		}

		public void onFailure(Throwable caught) {
		}
	};

	private void showEventRooms(List<PacketRoomKey> eventRooms) {
		final PopupPanelEventRooms popup = new PopupPanelEventRooms(this, eventRooms);
		popup.setPopupPosition(buttonShowEventRooms.getAbsoluteLeft(), buttonShowEventRooms.getAbsoluteTop());
		popup.show();
	}

	@Override
	public void onClick(ClickEvent event) {
		final Object sender = event.getSource();
		if (sender == buttonGameVsCom || sender == buttonGameAllClass || sender == buttonGameEvent || sender == buttonGameTheme) {
			// プレイヤー登録
			if (!checkContents()) {
				return;
			}

			if (sender == buttonGameEvent) {
				final StringBuffer sb = new StringBuffer();
				sb.append("イベント名 ： ").append(getEventName()).append("\n\nジャンル ：");

				final int genre = getGenre();
				for (int i = 0; i < Constant.NUMBER_OF_GENRE; ++i) {
					if ((genre & (1 << i)) != 0) {
						sb.append(" ").append(Constant.NAMES_OF_GENRE[i]);
					}
				}

				sb.append("\n\n形式 ：");

				final int type = getType();
				for (int i = 0; i < Constant.NUMBER_OF_TYPE_WITH_RANDOM; ++i) {
					if ((type & (1 << i)) != 0) {
						sb.append(" ").append(Constant.NAMES_OF_TYPE_WITH_RANDOM_FLAG[i]);
					}
				}

				sb.append("\n\nこの条件でイベント戦を行ないます。\n同じ条件を指定したプレイヤーとのみマッチングします。\nよろしいですか？");

				if (!Window.confirm(sb.toString())) {
					return;
				}
			}

			setEnabled(false);

			final UserData record = UserData.getInstance();
			record.setPlayerName(textBoxPlayerName.getText().trim());
			record.setLevelName(listBoxLevelName.getSelectedIndex());
			record.setLevelNumber(listBoxLevelNumber.getSelectedIndex());
			record.setPrefecture(listBoxPrefecture.getSelectedIndex());
			record.setGenre(getGenre());
			record.setType(getType());
			record.setGreeting(getGreeting());
			record.setMultiGenre(getMultiGenre());
			record.setMultiType(getMultiType());
			record.setDifficultSelect(getDifficultSelect());
			record.setNewProblem(getNewProblem());
			record.setPublicEvent(getPublicEvent());
			record.save();

			final int sessionType;
			if (sender == buttonGameVsCom) {
				sessionType = SceneLobby.SESSION_TYPE_VS_COM;
			} else if (sender == buttonGameAllClass) {
				sessionType = SceneLobby.SESSION_TYPE_WHOLE;
			} else if (sender == buttonGameEvent) {
				sessionType = SceneLobby.SESSION_TYPE_EVENT;
			} else if (sender == buttonGameTheme) {
				sessionType = SceneLobby.SESSION_TYPE_THEME;
			} else {
				sessionType = SceneLobby.SESSION_TYPE_VS_COM;
			}

			// 全体戦では手書きクイズを出さない
			int type = getType();
			if (sessionType == SceneLobby.SESSION_TYPE_WHOLE) {
				type &= ((1 << Constant.TYPE_TEGAKI) ^ (-1));
			}

			if (type == 0) {
				Window.alert("手書きクイズはβ版のため全体対戦ではお使いいただけません");
				setEnabled(true);
				return;
			}
			setType(type);

			scene.register(sessionType);

		} else if (sender == buttonShowEventRooms) {
			showEventRooms();
		}
	}
}
